package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"os"
	"regexp"
	"strings"
)

var target = []byte("https://m.bqg226.com")

func get(url string) []byte {
	resp, err := http.Get(url)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return nil
	}
	defer resp.Body.Close()
	content, err := io.ReadAll(resp.Body)
	return content
}

func File_put_contents(file string, content []byte) {
	pfile, err := os.Create(file)
	if err != nil {
		fmt.Println(err)
		return
	}
	pfile.Write(content)
	defer pfile.Close()
}

func getContent(s []byte) []byte {
	r1, _ := regexp.Compile(`<div id="chaptercontent" class="Readarea ReadAjax_content">([\s\S]+?)<p class="noshow">`)
	f1 := r1.FindSubmatch(s)

	content := string(f1[1])
	content = strings.ReplaceAll(content, "<br />", "\n")
	content = strings.ReplaceAll(content, "请收藏：https://m.bqg226.com", "")
	content = strings.TrimSpace(content)
	return []byte(content)
}

func getNextUrl(s []byte) []byte {
	r2, _ := regexp.Compile(`<a href="(.+?)" id="pb_next" class="Readpage_down js_page_down">`)
	f2 := r2.FindSubmatch(s)
	next := f2[1]
	return next
}

func getNextFileName(s []byte) []byte {
	r3, _ := regexp.Compile(`/([0-9_]+?)\.html`)
	f3 := r3.FindSubmatch([]byte(s))
	if len(f3) <= 1 {
		return nil
	}
	fileName := f3[1]
	return fileName
}

func getNextSecName(s []byte) []byte {
	var secName []byte
	if i := strings.Index(string(s), "_"); i >= 0 {
		secName = s[:i]
	} else {
		secName = s
	}
	return secName
}

func array_merge(pb ...[]byte) []byte {
	return bytes.Join(pb, []byte(""))
}

func main() {
	var secName = []byte("1")
	var nowContent []byte
	var nextUrl []byte
	nextUrl = []byte("https://m.bqg226.com/bqg/11136/1.html")
	for {
		fmt.Printf("正在下载第%s章...", secName)
		var s []byte
		for {
			s = get(string(nextUrl))
			if s != nil {
				break
			}
		}
		content := getContent(s)
		nextUrl = getNextUrl(s)
		nextFileName := getNextFileName(nextUrl)
		if nextFileName == nil {
			fmt.Println("全书已下载完成！")
			nowContent = array_merge(nowContent, content)
			File_put_contents("novel/ppyx/"+string(secName)+".txt", nowContent)
		} else {
			nextSecName := getNextSecName(nextFileName)
			if !bytes.Equal(secName, nextSecName) {
				nowContent = array_merge(nowContent, content)
				File_put_contents("novel/ppyx/"+string(secName)+".txt", nowContent)
				nowContent = make([]byte, 0)
				secName = nextSecName
				fmt.Println("下载完成！")
			} else {
				nowContent = array_merge(nowContent, content)
			}
			nextUrl = array_merge(target, nextUrl)
		}
	}
}
